<?php

/**
 * 角色管理
 * @author hfc
 * time 2015-7-5
 */

namespace apps\admin\controllers;
if( !defined( 'APP_ROOT' ) ){ echo 'Direct Access Deny!'; return; }

use enums\PriEnums;

use apps\admin\models\PriPris;
use apps\admin\models\PriRoles;
use apps\admin\models\PriRolesPris;
use enums\DBEnums;;
use Phalcon\Mvc\Model\Resultset;
use helpers\TimeUtils;
use apps\admin\models\PriUsers;
use apps\admin\ext\AdminBaseController;
class RolesController extends AdminBaseController{
    private $pris = array();
    
    public function initialize()
    {            
        parent::initialize();
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '角色列表页' )	
     * @method( method = 'indexAction' )
     * @op( op = 'r' )		
    */
    public function indexAction()
    {
        $this->view->rolesList = PriRoles::find( array( 
                        'delsign=' . DBEnums::DELSIGN_NO . 
        				' and id !=' . PriEnums::SUPER_ADMIN_ID . ' and id !=' . $this->userInfo[ 'role_id' ],
                        'columns' => 'id,name,descr',
                        'order' => 'uptime desc',
                        'hydration' => Resultset::HYDRATE_ARRAYS,
                    ));
        
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '编辑角色界面显示' )	
     * @method( method = 'editAction' )
     * @op( op = '' )		
    */
    public function editAction()
    {
        $id =  $this->request->getQuery( 'id', 'int' )  ;
      
        if( $id )
        {
	        $priRole = PriRoles::findFirst( array( 'id=?0 and delsign=' . DBEnums::DELSIGN_NO, 'bind' => array( $id ) ) );
	        if( $priRole )
	        {
	            $this->view->role = $priRole->toArray();
	            //当前角色包含的所有权限
	            $rolePris = array();
	            foreach( $priRole->priRolesPris as $item )
	            {
	            	if( ! $item->delsign )
	            	{
		                $rolePris[ $item->priid ] =  $item->id;
	            	}
	            }
	            $this->view->rolePris = $rolePris;
	        }
        }
      
        $this->view->pris = $this->_getPriTree();
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2016-07-05' )
     * @comment( comment = '查看自己所在组的角色，和自己所创建的角色' )
     * @method( method = 'readAction' )
     * @op( op = '' )
     */
    public function readAction()
    {
    	$this->editAction();
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = '添加角色界面显示' )	
     * @method( method = 'addAction' )
     * @op( op = '' )		
    */
    public function addAction()
    {
        $this->view->pris = $this->_getPriTree();
        $this->view->pick( 'roles/edit' );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax请求 更新角色' )	
     * @method( method = 'updateAction' )
     * @op( op = 'c' )		
    */
    public function updateAction()
    {
        if( ! $this->csrfCheck() ){ return false; }
        
        $roleId = $this->request->getPost( 'roleId', 'int' );
        $data[ 'name' ] = $this->request->getPost( 'roleName', 'trim' );
        $data[ 'descr' ] = $this->request->getPost( 'roleDescr', 'string' );
        $data[ 'type' ] = $this->request->getPost( 'type', 'int' );
        $arrPri = $this->request->getPost( 'add' ); //添加新数据
        $arrDelId = $this->request->getPost( 'del' );//删除老数据
        $data[ 'uptime' ] = TimeUtils::getFullTime();
        $role = PriRoles::findFirst( [ 'id=?0 and delsign=' . DBEnums::DELSIGN_NO, 'bind' => [ $roleId ] ]);
        $status = false;
        
        if( $role->update( $data ) )
        {
            if( ! empty( $arrDelId )) //删除
            {
                $str  = implode( ',', $arrDelId );
                $status = PriRolesPris::find( [ 'id in (' . $str . ')' ])->delete();
            }
            if( ! empty( $arrPri )) //添加
            {
               $model = new PriRolesPris();
               $status = $model->addData( $roleId, $arrPri );
            }
            
            if(  empty( $arrDelId ) && empty( $arrPri ) ) //二者都沒有
            {
                return $this->success( '更新成功' );
            }
            
            
            if( $status ) //有修改，就 进行acl的修改
            {
                if( $this->setAcl( $roleId ) )
                {
                	return $this->success( '更新成功' );
                }
                else
                {
                    return $this->error( '更新acl失败' );
                }
            }
        }
       
        return $this->error( '更新失败' );
        
    }

    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax请求 删除角色' )	
     * @method( method = 'deleteAction' )
     * @op( op = 'd' )		
    */
    public function deleteAction()
    {
        if( ! $this->csrfCheck() ){ return false; }
        $id = $this->request->getPost( 'id', 'int' );
        
        if( $id )
        {
            $priRoles = PriRoles::findFirst( array( 'id=?0 and delsign=' . DBEnums::DELSIGN_NO, 'bind' => array( $id )));
            if( $priRoles )
            {
            	$isUse = PriUsers::findFirst( array( 'role_id=?0 and delsign=' . DBEnums::DELSIGN_NO, 'bind' => array( $id ) ) );
            	if( $isUse)
            	{
            		return $this->error( '正在使用，请勿删除！' );
            	}
            	
                $isRoles = $priRoles->delete();
                $isPris = $priRoles->priRolesPris->delete();
                if( $isPris && $isRoles )
                {
                   return $this->success( '删除成功' );
                }
            }
        }
        return $this->error( '删除失败' );
    }
    
    /**
     * @author( author='hfc' )
     * @date( date = '2015-8-24' )
     * @comment( comment = 'ajax 请求 添加一个新角色' )	
     * @method( method = 'insertAction' )
     * @op( op = 'c' )		
    */
    public function insertAction()
    {
        if( ! $this->csrfCheck() ){ return false; } //csrf检验
        
        $data[ 'name' ] = $this->request->getPost( 'roleName', 'trim' );
        $data[ 'descr' ] = $this->request->getPost( 'roleDescr', 'string' );
        $data[ 'type' ] = $this->request->getPost( 'type', 'int' );
        $add = $this->request->getPost( 'add' );
        $data[ 'addtime' ]  = $data[ 'uptime' ] = TimeUtils::getFullTime();
        $data[ 'delsign' ]  = DBEnums::DELSIGN_NO;
        
        //判断是否角色名是否重复
        $priRole = PriRoles::findFirst( [ 'name=?0 and delsign=' . DBEnums::DELSIGN_NO , 'bind' => [ $data[ 'name']]] );
        if( $priRole ) 
        {
            return $this->error( '已经角色存在了' );
        }
        
        $role = new PriRoles();
        if( $role->save( $data ) && (! empty( $add)) )
        {
            $model = new PriRolesPris();
            if( $model->addData( $role->id, $add ) )
            {
            	if( $this->setAcl( $role->id ) )
            	{
                	return $this->success( '添加成功' );
            	}
            }
        }
        return $this->error( '添加失败');
    }
    
    /**
     * 得到管理后台权限项
     * param number $parentid 
     */
    private function _getPriTree( )
    {
        $arrPris = [];
    	if( $this->isSuperAdmin ) //超级管理员下的权限项
    	{
//     		$where = 'delsign='. DBEnums::DELSIGN_NO . ' and (type = ' . PriEnums::PRI_ACTION . ' or type = ' . PriEnums::PRI_MENU . ')';
			$condition = 'delsign=' . DBEnums::DELSIGN_NO;
	        $apris = PriPris::find( array( $condition, 'columns' => 'id,name,pid', 'order' => 'id' ) )->toArray();
	        
            foreach( $apris as $item )
            {
                $arrPris[ $item[ 'pid'] ][] = $item; 
            }
    	}
    	else //查看该角色下的所有的权限项
    	{
    		$objRole = new PriRolesPris();
    		$arrPris = $objRole->getRolePris( $this->userInfo[ 'role_id' ] );
    	}
        return $arrPris;
    }
    
}
